﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddMaterialGroupForm : XtraForm
    {
        public AddMaterialGroupForm()
        {
            InitializeComponent();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                MaterialCode = textEditCode.Text,
                MaterialName = textEditName.Text,
                MaterialMsg = textEditMsg.Text,
                MaterialType = comboBoxEditType.Text,
                Routing = textEditProcessRoute.Text,
                CreatedBy = "wyj"
            };

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri("https://localhost:7274/");
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("api/Material/AddMaterial", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddMaterialGroupForm_Load(object sender, EventArgs e)
        {

        }
    }
}